package com.exteam.common.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.exteam.common.util.CommLogger;
import com.exteam.common.view.dialog.LoadingDialog;
import com.exteam.common.view.dialog.MessageDialog;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

/**
 * 所有Activity父类
 * 提供载入Dialog,MainHandler及SubHanlder(暂时不启动)
 *
 * @author sean.yanghy
 * @version v1.0
 * @created 2014-11-20 13:56:23
 */

public abstract class BaseActivity extends Activity implements View.OnClickListener {

    // LoadingDialog
    protected LoadingDialog loadingDialog;
    protected MessageDialog messageDialog;
    protected String subLogTag = "BaseAct";

    public static ArrayList<BaseActivity> listActivity = new ArrayList<BaseActivity>(5);

    protected static final int MSG_EXCEPTION = -100;

    // 主控制器
    public BaseController baseController;
    protected List<BaseController> baseControllers = new ArrayList<BaseController>(3);

    // 子线程及其Handler
    //protected HandlerThread subThread;
    //protected Handler subHandler;


    // 主线程Handler
    public Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case LoadingDialog.MSG_SHOW:
                    if (loadingDialog != null) loadingDialog.show((String) msg.obj);
                    break;
                case LoadingDialog.MSG_CLOSE:
                    if (loadingDialog != null) loadingDialog.dissmis();
                    break;
                case MessageDialog.MSG_SHOW:
                    if (messageDialog != null) messageDialog.show((String) msg.obj);
                    break;
                case MessageDialog.MSG_CLOSE:
                    if (messageDialog != null) messageDialog.dissmis();
                    break;
            }
            processMainHandleMessage(msg);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        listActivity.add(this);
        loadingDialog = new LoadingDialog(this);
        messageDialog = new MessageDialog(this);
        CommLogger.initLogger(this.getClass().getSimpleName());
    }

    public Handler getMainHandler() {
        return mainHandler;
    }

    public LoadingDialog getLoadingDialog() {
        return loadingDialog;
    }

    public MessageDialog getMessageDialog() {
        return messageDialog;
    }


//	public void initSubThreadAndHandler(){
//		subThread = new HandlerThread("SubThread");
//		subThread.start();
//		//DataLog.info(subLogTag+"SubThread start:");
//		subHandler = new Handler(subThread.getLooper()){
//
//			@Override
//			public void handleMessage(Message msg) {
//				// TODO Auto-generated method stub
//				super.handleMessage(msg);
//				processSubHandleMessage(msg);
//			}
//
//		};
//	}


//	public void closeSubThreadAndHandler(){
//		if(subThread !=null){
//			subThread.quit();
//		}
//
//		//DataLog.info(subLogTag+"subThread quit:");
//		subHandler = null;
//		subThread = null;
//	}

    protected void sendMainHandlerMessage(int what, Object obj) {
        Message msg = mainHandler.obtainMessage();
        msg.what = what;
        msg.obj = obj;
        mainHandler.sendMessage(msg);
    }

    // 子类重写，实现自己的消息处理
    protected void processMainHandleMessage(Message msg) {
        switch (msg.what) {
            case MSG_EXCEPTION:
                processException((IOException) msg.obj);
                break;

            default:
                break;
        }
        CommLogger.d("baseact processMainHandleMessage");
        if (baseController != null) {
            baseController.processMainHandleMessage(msg);
        }
        for (BaseController baseCon : baseControllers) {
            baseCon.processMainHandleMessage(msg);
        }
    }

    // 子类重写，实现自己的异常处理
    protected void processException(IOException ioException) {
        if (ioException instanceof SocketTimeoutException) {
            //toast(R.string.connect_timeout);
        } else {
            //toast(R.string.connect_exception);
        }
        ioException.printStackTrace();
    }

    // 子类重写，实现自己的消息处理
    protected void processSubHandleMessage(Message msg) {

    }

    // 子类重写，实现自己的点击试图事件
    public void viewOnClick(View v) {

    }

    // 子类重写，实现自己的点击试图事件
    public void onViewClick(View v) {
        CommLogger.d("BaseActivity onViewClick");
        if (baseController != null)
            baseController.onViewClick(v);
        for (BaseController baseCon : baseControllers) {
            baseCon.onViewClick(v);
        }
    }

    @Override
    public void onClick(View v) {

    }

    // 跳转页面
    public void startDataActivity(Class toActivity) {
        startActivity(new Intent(this, toActivity));
        //overridePendingTransition(R.anim.comm_push_left_in, R.anim.comm_push_left_out);
    }

    // 跳转页面
    public void startDataActivity(Intent intent) {
        startActivity(intent);
        //overridePendingTransition(R.anim.comm_push_left_in, R.anim.comm_push_left_out);

    }

    // 跳转页面
    public void startDataActivityForResult(Class toActivity, int reqCode) {
        super.startActivityForResult(new Intent(this, toActivity), reqCode);
        //overridePendingTransition(R.anim.comm_push_left_in, R.anim.comm_push_left_out);
    }

    public void finishDataActivity() {
        finish();
    }

    public void finishDataActivity(int resultCode) {
        finishActivity(resultCode);
    }

    public void toast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    public void toast(int message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    public String getSubLogTag() {
        return subLogTag;
    }

    public void setSubLogTag(String subLogTag) {
        this.subLogTag = subLogTag;
    }

    public void setMainHandler(Handler mainHandler) {
        this.mainHandler = mainHandler;
    }


//	public Handler getSubHandler() {
//		return subHandler;
//	}
//	public void setSubHandler(Handler subHandler) {
//		this.subHandler = subHandler;
//	}


    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        if (baseController != null)
            baseController.onRestart();
        for (BaseController baseCon : baseControllers) {
            baseCon.onRestart();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (baseController != null)
            baseController.onStart();
        for (BaseController baseCon : baseControllers) {
            baseCon.onStart();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommLogger.d("onResume：" + this.getClass().getSimpleName());
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        if (baseController != null)
            baseController.onResume();
        for (BaseController baseCon : baseControllers) {
            baseCon.onResume();
        }
    }

    protected void onPause() {
        super.onPause();
        CommLogger.d(this.getClass().getSimpleName());
        MobclickAgent.onPageEnd("onPause:" + this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        if (baseController != null)
            baseController.onPause();
        for (BaseController baseCon : baseControllers) {
            baseCon.onPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (baseController != null)
            baseController.onStop();
        for (BaseController baseCon : baseControllers) {
            baseCon.onStop();
        }
    }

    public void onDestroy() {
        //closeSubThreadAndHandler();
        //DataLog.info(subLogTag+"remove act");
        super.onDestroy();
        if (listActivity != null)
            listActivity.remove(this);
        if (baseController != null) {

            baseController.onDestroy();
            baseController.clear();
        }
        for (BaseController baseCon : baseControllers) {
            baseCon.onDestroy();
            baseCon.clear();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (baseController != null) {
            baseController.onActivityResult(requestCode, resultCode, data);
        }
        for (BaseController baseCon : baseControllers) {
            baseCon.onActivityResult(requestCode, resultCode, data);
        }
    }
}
